package interpreter;

public class SchemePair {

	private Object car;
	private Object cdr;

	public SchemePair(Object car, Object cdr) {
		this.car = car;
		this.cdr = cdr;
	}

	public Object getCar() {
		return car;
	}

	public Object getCdr() {
		return cdr;
	}

	@Override
	public String toString() {
		if (isList())
			return asListToString();
		return "(" + car.toString() + " . " + cdr.toString() + ")";
	}

	private boolean isList() {
		return cdr == EmptyList.instance
				|| (cdr instanceof SchemePair && ((SchemePair) cdr).isList());
	}

	private String asListToString() {
		String listWithExtraSpaceAtTheEnd = recursiveCarToString(this);
		return "(" + listWithExtraSpaceAtTheEnd.trim() + ")";
	}

	private String recursiveCarToString(Object list) {
		if (list == EmptyList.instance)
			return "";
		return ((SchemePair) list).car.toString() + " "
				+ recursiveCarToString(((SchemePair) list).cdr);
	}
}
